/**
 * Created by Administrator on 2018/10/28.
 */


function getHomeInfo(id) {
    //请求主页信息
    ajax({
        url: 'app/field/userField',
        data: {
            userId: id || getUserId()
        },
        success: function (d) {
            initFieldInfo(d, id);
            if (isMineField) {
                initMineInfo(d);
                // if (isFirst) {
                initMyDetailInfo(d);
                //请求商城信息
                getMallInfo();
                // }
            } else {
                // if (isFirst)
                initFriendInfo(d);
            }
            isFirst = false;
        }
    })
}

//刷新信息
function refreshInfo(data) {
    var $fieldContainer = $('#field-container');
    var $fieldRightContainer = $('#field-right-container');
    var data = data.botanyList;
    var leftFieldHTML = '';
    var rightFieldHTML = '';
    data.forEach(function (d, i) {
        var itemHTML = ' <div class="first field-content"> ' +
            '<div class="field-item" data-seedId="' + d.id + '">' +
            '   <div class="field-img  first">' +
            '       <img class="fieldItem-status step1 ' + (d.seedType == 0 ? "isShow" : '') + '" src="../images/grapeStep1.png"/>' +
            '       <img class="fieldItem-status step2 ' + (d.seedType == 1 ? 'isShow' : '') + '" src="../images/grapeStep2.png"/>' +
            '       <img class="fieldItem-status step3 ' + (d.seedType == 2 ? 'isShow' : '') + '" src="../images/grapeStep3.png"/>' +
            '       <img class="fieldItem-status step4 ' + (d.seedType == 3 ? 'isShow' : '') + '" src="../images/grapeStep4.png"/>' +
            '       <img data-seedId="' + d.id + '" class="fieldItem-isStore step5 ' + (d.seedType == 3 ? 'isShow' : '') + '" src="../images/icon-steal.png"/>' +
            '       <div class="steal-num"><img  src="../images/stealSuccess-num.png"/> </div>' +
            '       </div>' +
            '</div></div>';
        if (i > 5 && i < 9) {
            rightFieldHTML += itemHTML;
        } else if (i < 6) {
            leftFieldHTML += itemHTML;
        }
    });

    //增加种的图标
    var addIconHTML = '<div class="first field-content"><div class="field-item"> <div class="field-img  first"><img class="add-field" src="../images/icon-addField.png"/></div></div></div>';
    if (data.length > 5 && data.length < 9) {
        rightFieldHTML += addIconHTML;
    } else if (data.length < 6) {
        leftFieldHTML += addIconHTML;
    }
    $fieldContainer.html(leftFieldHTML);
    $fieldRightContainer.html(rightFieldHTML);
}

//初始化田地信息
function initFieldInfo(data, friendId) {
    var $fieldContainer = $('#field-container');
    var $homeContent = $('.home-content');
    refreshInfo(data);
    if (data.isHaveDog) {
        $('#dog-dialog').show();
    } else {
        $('#dog-dialog').hide();
    }
    //收取或偷取金币
    $homeContent.find('.fieldItem-isStore').off('click').on('click', function () {
        var $this = $(this);
        if (!$this.attr('data-seedId')) return;
        if (isMineField) {
            getStealResult();
        } else {
            ajax({
                url: 'app/field/beforeStealingGold',
                data: {
                    friendId: friendId
                },
                success: function (d) {
                    getStealResult();
                },
                fail: function (d) {
                    if (d.message) {
                        if (d.message.code && d.message.code == 313) {
                            showConfirmDialog('您的好友家有狗，是否要使用打狗棒打跑？', function () {
                                ajax({
                                    url: 'app/field/useStage',
                                    data: {
                                        type: 'DA_DOG_GUN'
                                    },
                                    success: function (d) {
                                        _alert('使用成功');
                                        $('#dog-dialog').hide();
                                    }
                                })
                            });
                        } else {
                            _alert(d.message.msg);
                        }
                    }

                }
            })
        }

        function getStealResult() {
            ajax({
                url: 'app/field/stealingGold',
                data: {
                    seedId: $this.attr('data-seedId')
                },
                success: function (d) {
                    _alert(isMineField ? '收取成功' : '偷取成功');
                    // if (isMineField) {
                    getHomeInfo();
                    // }
                }
            })
        }

        //收金币

        return false;
    });
    //铲地
    $homeContent.find('.field-item').off('click').on('click', function () {
        var $this = $(this);
        if (!isChanDi) return;
        if (!$this.attr('data-seedId')) return;
        showConfirmDialog('确定要铲除这颗植物吗？', function () {
            ajax({
                url: 'app/field/chandi',
                data: {
                    seedId: $this.attr('data-seedId')
                },
                success: function (d) {
                    getHomeInfo();
                    _alert('铲除成功');
                }
            })
        });
        return false;
    });
    //点击种字  种地
    $homeContent.find('.add-field').off('click').on('click', function () {
        var $this = $(this);
        ajax({
            url: 'app/field/useStage',
            data: {
                type: 'PU_TAO_ZHONG_ZI'
            },
            success: function (d) {
                _alert('使用成功');
                getHomeInfo();
            }
        })
    })
}

function showConfirmDialog(text, callback) {
    var $quitGameDialog = $('#quit-game');
    $quitGameDialog.find('.msg-content').html(text);
    $quitGameDialog.show();
    $quitGameDialog.find('.edit-game').off('click').on('click', function () {
        $quitGameDialog.hide();
        callback();
    });
    $quitGameDialog.find('.close-editDialog').off('click').on('click', function () {
        $quitGameDialog.hide();
    });
}

//请求商城并初始化信息
function getMallInfo() {
    ajax({
        url: 'app/prop/getPropList',
        data: {},
        success: function (d) {
            //初始化商城信息
            var $propsMallDialog = $('#propsMall-dialog');
            var $goodsList = $propsMallDialog.find('.goods-list');
            var $notice = $propsMallDialog.find('.notice');

            $notice.html('公告：' + (d.notice || '商城公告'));
            var listHTML = '';
            d.videoList.forEach(function (d) {
                var itemHTML = '<li>' +
                    '<div class="img-box"><img class="goods-pic" src="' + getGoodsImgUrl(d.type) + '" </div>' +
                    '<div class="info-box">' +
                    '<h4 class="title">' + d.name + '</h4>' +
                    '<p><img src="../images/icon-gold.png"/><span>' + d.price + '</span></p>' +
                    '<div class="buyGoods-btn">' +
                    '<button class="toBuy-btn" data-type="' + d.type + '" data-id="' + d.id + '" data-price="' + d.price +
                    '" data-name="' + d.name + '">' + (d.type == 'HONG_JIU_MALL' ? '进入' : '购买') + '</button>' +
                    '</div>' +
                    '</div></li>';
                listHTML += itemHTML;
            });
            $goodsList.html(listHTML);
            var $propsMallBuyDialog = $('#propsMall-buyDialog');
            var $num = $propsMallBuyDialog.find('.buy-num span');
            var $price = $propsMallBuyDialog.find('.buyGoods-price');
            var $buyBtn = $propsMallBuyDialog.find('.buy-btn');
            var $buyMinus = $propsMallBuyDialog.find('.buy-minus');
            var $buyAdd = $propsMallBuyDialog.find('.buy-add');
            //减少购买数量
            $propsMallBuyDialog.find('.buy-minus').off('click').on('click', function () {
                var $this = $(this);
                var num = $num.text();
                if (num == 1) {
                    return
                } else {
                    if (num == 2) {
                        $buyMinus.find('img').attr('src', '../images/buyGoods-minusDis.png');
                    }
                    $num.text(--num);
                    $price.text($buyBtn.attr('data-price') * num);
                }
            });
            //点击确定购买
            $propsMallBuyDialog.find('.buy-btn').off('click').on('click', function () {
                var $this = $(this);
                ajax({
                    url: 'app/prop/submitOrder',
                    data: {
                        propertyId: $this.attr('data-id'),
                        count: $num.text()
                    },
                    success: function (d) {
                        _alert(d);
                        getHomeInfo();
                        $propsMallBuyDialog.hide();
                    }
                })
            });
            //增加购买数量
            $propsMallBuyDialog.find('.buy-add').off('click').on('click', function () {
                var $this = $(this);
                var num = $num.text();
                if (num == 1) {
                    $buyMinus.find('img').attr('src', '../images/buyGoods-minus.png');
                }
                $num.text(++num);
                $price.text($buyBtn.attr('data-price') * num);
            });
            //点击商品列表购买
            $propsMallDialog.find('.toBuy-btn').off('click').on('click', function () {
                var $this = $(this);
                if ($this.attr('data-type') == 'HONG_JIU_MALL') {
                    window.location.href = 'mall.html';
                    return;
                }
                $propsMallBuyDialog.show();
                $propsMallBuyDialog.find('.buy-num span').text('1');
                $propsMallBuyDialog.find('.buy-minus img').attr('src', '../images/buyGoods-minusDis.png').addClass('dis');
                $propsMallBuyDialog.find('.buyGoods-price').text($this.attr('data-price'));
                $propsMallBuyDialog.find('.buy-btn').attr({
                    'data-id': $this.attr('data-id'),
                    'data-price': $this.attr('data-price')
                });
            })
        }
    })
}


//初始化道具商城购买商品
function initMallGoods() {
    var $propsMallDialog = $('#propsMall-dialog');
    $propsMallDialog.on('click', '.goods-buyBtn', function () {
        var $this = $(this);
        openBuyDialog({
            price: $this.attr('data-price'),
            name: $this.attr('data-name'),
            id: $this.attr('data-id'),
        })
    });

    function openBuyDialog(opts) {
        var $propsMallBuyDialog = $('#propsMall-buyDialog');
        $propsMallBuyDialog.show();
        $propsMallBuyDialog.find('.buyGoods-price').text(opts.price);
    }

    //商城购买弹窗


}

//初始化我的基本信息
function initMineInfo(d) {
    var $mineInfo = $('.mine-info');
    var $mineAvatar = $mineInfo.find('.user-avatar');
    var $mineUsername = $mineInfo.find('.username');
    var $mineExperience = $mineInfo.find('.experience .experience');
    var $mineGold = $mineInfo.find('.gold-balance');
    var $mineGrapeNum = $mineInfo.find('.grape-num');
    $mineAvatar.attr('src', d.imageUrl || '../images/default-avatar.png');
    $mineUsername.text(d.userName);
    $mineGold.text(d.gold);
    $mineExperience.text(d.growthValue)
}

//初始化我的好友基本信息
function initFriendInfo(d) {
    var $friendInfo = $('.friend-info');
    var $friendAvatar = $friendInfo.find('.user-avatar');
    var $friendUsername = $friendInfo.find('.username');
    var $friendGold = $friendInfo.find('.gold-balance');
    var $friendExperience = $friendInfo.find('.experience .experience');
    $friendAvatar.attr('src', d.imageUrl || '../images/default-avatar.png');
    $friendUsername.text(d.userName);
    $friendGold.text(d.gold);
    $friendExperience.text(d.growthValue);
}

//偷金币
function initStealGold() {
    var $stealGold = $('#steal-gold');
    $stealGold.on('click', function () {
        //todo 偷金币
    });
}

//打开好友模块
function initOpenMyFriends() {
    var $searchFriendBox = $('#searchFriend-box');
    var $rightCenter = $('.rightCenter-box');
    var $openMyFriends = $('#open-myFriends');
    var $keywords = $searchFriendBox.find('.search-box input');
    var $resultBox = $searchFriendBox.find('.result-box');
    var $noResult = $searchFriendBox.find('.no-result');
    $searchFriendBox.on('click', '.search-btn', function () {
        if (!$keywords.val()) {
            _alert('请先输入要搜索的账号');
            return;
        } else {
            ajax({
                url: 'app/user/search',
                data: {
                    mobile: $keywords.val()
                },
                success: function (d) {
                    if (d.userId) {
                        var html = '<div class="result-user"> <div class="resultUser-content"> ' +
                            '<div class="resultImg-box"><img src="' + d.imageUrl + '"/></div>' +
                            '<div class="result-info"><p>' + d.userName + '</p><p><button class="addFriend-btn" data-mobile="' + $keywords.val() + '">添加</button></p></div></div></div>';
                        $resultBox.html(html).show();
                        $noResult.hide();
                    } else {
                        $resultBox.hide();
                        $noResult.show();
                    }
                }
            })
        }
    });
    //添加朋友
    $searchFriendBox.on('click', '.addFriend-btn', function () {
        var $this = $(this);
        var mobile = $this.attr('data-mobile');
        if (!mobile) return;
        if ($this.text() == '已添加') return;
        if (mobile == myMobile) {
            _alert('不能添加自己为好友');
            return;
        }
        ajax({
            url: 'app/friend/addFriend',
            data: {
                friendNo: mobile
            },
            success: function (d) {
                _alert('添加成功');
                $resultBox.find('button').text('已添加');
            }
        })
    });
    //打开我的好友模块
    $rightCenter.on('click', function () {
        $('#myFriendsList-box').show();
        initMyFriendsList();
        // $('#searchFriend-box').show();
    });
    //初始化我的好友事件
    initMyFriendListClick();
    $openMyFriends.on('click', function () {
        //todo 打开我的好友
    });
}

function getHisFriendMsg(dataId) {
    var $myFriendList = $('#myFriendsList-box');
    // if ($myFriendList.isHidden()) return;
    ajax({
        url: 'app/friend/newsList',
        data: {
            fromId: getUserId(),
            toId: dataId || selectedFriend
        },
        success: function (d) {
            var html = '';
            // var len = $myFriendList.find('.talk-detail ul li').length;
            // var newArray = [];
            // if (d.newsList.length > len) {
            //     newArray = d.newsList.splice(len);
            // }
            d.newsList.forEach(function (d) {
                var item = '<li class="' + (d.from == getUserId() ? 'mine-msg' : 'friend-msg') + ' "><span>' + d.body + '</span></li>';
                html += item;
            });
            $myFriendList.find('.talk-detail ul').html(html);
        }
    })
}

function initMyFriendListClick() {
    var $myFriendList = $('#myFriendsList-box');
    //打开好友聊天
    $myFriendList.on('click', '.friend-item', function () {
        var $this = $(this);
        if ($this.hasClass('active')) return;
        $this.addClass('active').siblings().removeClass('active');
        //todo  对接历史消息列表
        // getHisFriendMsg($this.attr('data-id'));
        window.selectedFriend = $this.attr('data-id');
        $myFriendList.find('.talk-detail ul').html('');
        if (timer) clearInterval(timer);
        timer = setInterval(function () {
            getHisFriendMsg(selectedFriend);
        }, 1000);
    });
    //去好友庄园
    $myFriendList.on('click', '.friend-item img', function () {
        $('.dialog_content').hide();
        $('#bottom-toolbar').hide();
        $('.back-home').show();
        $('.rightCenter-box').hide();
        $('.friend-info').show();
        isMineField = false;
        getHomeInfo($(this).parents('.friend-item').attr('data-id'));
        return false;
    });
    $myFriendList.on('click', '.addFriend-box', function () {
        $('#searchFriend-box').show();
    });
    //删除好友
    $myFriendList.on('click', '.delFriend-box', function () {
        var $activeItem = $myFriendList.find('.friend-item.active');
        if ($activeItem.length == 0) {
            _alert('请先选择要删除的好友');
            return;
        }
        ajax({
            url: 'app/friend/agreeFriend',
            data: {
                applyUserId: $activeItem.attr('data-id'),
                status: '3'
            },
            success: function (d) {
                _alert('删除成功');
                initMyFriendsList();
            }
        })
    });
    //给好友发送消息
    $myFriendList.on('click', '.send-btn', function () {
        var $this = $(this);
        var activeFriendId = $('#myFriendsList-box').find('.friend-item.active').attr('data-id');
        var $talkKeywords = $('#talk-keywords');
        if (!$talkKeywords.val()) {
            _alert('请先输入发送内容');
            return;
        }
        if (!activeFriendId) {
            _alert('请先选择接收信息的好友');
            return;
        }
        ajax({
            url: 'app/friend/sendMsg',
            data: {
                msg: $talkKeywords.val(),
                toId: activeFriendId
            },
            success: function (d) {
                var html = '<li class="mine-msg"><span>' + $talkKeywords.val() + '</span></li>';
                $myFriendList.find('.talk-detail ul').append(html);
                $talkKeywords.val('');
            }
        })
    });
}

//初始化好友列表html
function initMyFriendsList() {
    var $myFriendList = $('#myFriendsList-box');
    ajax({
        url: 'app/friend/friendList',
        data: {},
        success: function (d) {
            var html = '';
            d.friendList.forEach(function (d) {
                var item = '<div class="friend-item " data-id="' + d.friendUserId + '">' +
                    '<p><img src="' + (d.imgUrl || '../images/default-avatar.png') + '"/><span>' + d.friendUserName + '</span></p></div>';
                html += item;
            });
            $myFriendList.find('.friend-list').html(html);
            $myFriendList.find('.talk-detail ul').html('');
        }
    })
}

//底部导航
function initBottomBar() {
    var $bottomBar = $('#bottom-toolbar');
    $bottomBar.on('click', '.mall', function () {
        //todo 商城
        $('#propsMall-dialog').show();
    });
    $bottomBar.on('click', '.myProps', function () {
        //todo 去我的道具
        getMyPropsHTML();
    });
    //使用道具
    $('#myPropsMall-dialog').on('click', '.toBuy-btn', function () {
        var $this = $(this);
        ajax({
            url: 'app/field/useStage',
            data: {
                type: $this.attr('data-type')
            },
            success: function (d) {
                _alert('使用成功');
                getMyPropsHTML();
                getHomeInfo();
            }
        })
    });
    $bottomBar.on('click', '.shovel', function () {
        //todo 铲子
        isChanDi = !isChanDi;
    });
    $bottomBar.on('click', '.charge', function () {
        //todo 收取
    });
    $bottomBar.on('click', '.userCenter', function () {
        //todo 个人中心
        $('#myDetailInfo-box').show();
    });
}

function getMyPropsHTML() {
    ajax({
        url: 'app/prop/geUserPropList',
        data: {},
        success: function (d) {
            var html = '';
            d.userStagePropertyList.forEach(function (d) {
                var itemHTML = '<li>' +
                    '<div class="img-box"><img class="goods-pic" src="' + getGoodsImgUrl(d.type) + '" </div>' +
                    '<div class="info-box">' +
                    '<h4 class="title">' + d.name + '</h4>' +
                    '<p class="count"><span>×' + d.count + '</span></p>' +
                    '<div class="buyGoods-btn">' +
                    '<button class="toBuy-btn" data-type="' + d.type + '" data-id="' + d.id + '" data-price="' + d.price + '" data-name="' + d.name + '">使用</button>' +
                    '</div>' +
                    '</div></li>';
                html += itemHTML;
            });
            $('#myPropsMall-dialog').show();
            $('#myPropsMall-dialog').find('.goods-list').html(html).show();
        }
    })

}


//回家
function initBackHome() {
    var $backHome = $('#back-home');
    $backHome.on('click', function () {
        $('.dialog_content').hide();
        $('#bottom-toolbar').show();
        $('.back-home').hide();
        $('.rightCenter-box').show();
        $('.friend-info').hide();
        isMineField = true;
        getHomeInfo();
        return false;
    });
}


//我的资料弹窗
function initMyDetailInfo(d) {
    var $myDetailInfo = $('#myDetailInfo-box');
    $myDetailInfo.find('.myDetail-username').text(d.userName);
    $myDetailInfo.find('.myDetail-mobile').text(d.phone);
    window.myMobile = d.phone;
    $myDetailInfo.find('.myDetail-sex').text(d.sex == 1 ? '男' : '女');
}

//退出游戏
function initQuitGame() {
    var $quitGame = $('#quit-game');
    //todo 退出游戏
}

//获取商品图片地址
function getGoodsImgUrl(type) {
    var url = '';
    switch (type) {
        case 'TAI_DI':
            url = 'xiaogou';
            break;
        case 'DOG_HEAD':
            url = 'goutou';
            break;
        case 'DOG':
            url = 'dagou';
            break;
        case 'DA_DOG_GUN':
            url = 'goubang';
            break;
        case 'DOG_FOOD':
            url = 'gouliang';
            break;
        case 'DOG_PEN':
            url = 'goupen';
            break;
        case 'CHAN_SHI_CHAN':
            url = 'tieqiao';
            break;
        case 'ZUI_DOG_JIU':
            url = 'jiu';
            break;
        case 'FEI_LIAO':
            url = 'huafei';
            break;
        case 'PU_TAO_ZHONG_ZI':
            url = 'zhongzi';
            break;
        case 'HONG_JIU_MALL':
            url = 'hongjiu';
            break;
        default:
            break;
    }
    if (url) {
        return '../images/goods/' + url + '.png';
    }
}

function initFirstGuide() {
    var $fieldGuideBox = $('#fieldGuide-box');
    var textList = [
        '欢迎来到我的庄园，您可以点击下方商城进行道具购买',
        '我的背包可以进行道具使用，进行农场打理',
        '如果没有经营好，可以点击下方铲子，然后点击相应土地，即可进行铲除',
        '当植物成熟后，就可以点击植物上方的手型图标进行收取',
    ];
    $fieldGuideBox.find('.guide-text').text(textList[$fieldGuideBox.find('.guide-text').attr('data-index')]);
    $fieldGuideBox.on('click', function () {
        var $this = $(this);
        var $guideText = $this.find('.guide-text');
        var index = parseInt($guideText.attr('data-index'));
        if (index >= textList.length - 1) {
            $fieldGuideBox.hide();
        } else {
            $guideText.attr('data-index', index + 1);
            $guideText.text(textList[index + 1]);
        }

    });
}

function getGps() {
    var map, geolocation;
    map = new AMap.Map('container', {//加载地图，调用浏览器定位服务
        resizeEnable: true
    });
    map.plugin('AMap.Geolocation', function () {
        geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 5000,          //超过5秒后停止定位，默认：无穷大
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            buttonPosition: 'RB'
        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition();

        AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
        AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
    });

    function onComplete(data) {//解析定位结果
        var $myDetailInfo = $('#myDetailInfo-box');
        var city = '';
        if (data.info == 'SUCCESS') {
            if (data.formattedAddress.indexOf('市') > -1) {
                city = data.formattedAddress.split('市')[0] + '市';
            } else {
                city = '定位失败';
            }
        } else {
            city = '定位失败';
        }
        $myDetailInfo.find('.myDetail-address').text(city);
    }

    function onError(data) {//解析定位错误信息
        console.log("定位失败！");
        jwd = "113.734202,34.749687";//固定经纬度
        near(jwd);
    }
}

function loginOut() {
    $('#login-out').on('click', function () {
        showConfirmDialog('确定要退出账号么？', function () {
            removeUserInfo();
            window.location.href = 'login.html';
        });
    });
}

function recharge() {
    $('#mine-recharge').on('click', function () {
        window.location.href = 'http://server.yemanputao.com/payResult.html?userId='+getUserId()+'&token='+getToken();
    });
}

function initPageClick() {
    var $pageContent = $('#home-main');
    $pageContent.on('click', '.close-dialog', function () {
        $(this).parents('.dialog_content').eq(0).hide();
    });
    initStealGold();
    initOpenMyFriends();
    initBottomBar();
    initBackHome();
    initQuitGame();
    initFirstGuide();
    loginOut();
    recharge();
}

$(function () {
    window.isMineField = true;
    window.isChanDi = false;
    window.isFirst = true;
    window.timer = null;
    // $('#audio')[0].play();
    ajax({
        url: 'app/user/isFirstLogin',
        data: {},
        success: function (d) {
            if (d.isFirstLogin == 1) {
                $('#fieldGuide-box').show();
            } else if (d.isFirstLogin == 0) {
                $('#fieldGuide-box').hide();
            }
        }
    })
    getGps();
    getHomeInfo();
    initPageClick();
    $('#progressbar1').LineProgressbar({
        percentage: 100,
        fillBackgroundColor: '#9ae456',
        height: '1.5rem',
        radius: '1.5rem'
    });
    setTimeout(function () {
        $('.progressbar-box').hide();
        $('.home-content').show();
    }, 1000);
});